package com.ujs.leetcode.Intersection;

import java.util.*;

/**
 * @author zhangshihao
 * @create 2023-10-14 20:19
 * <p>
 * 350. 两个数组的交集 II
 * https://leetcode.cn/problems/intersection-of-two-arrays-ii/description/
 */
public class Intersection2 {
    public static void main(String[] args) {
        int[] nums1 = {1, 2, 2, 1};
        int[] nums2 = {2, 2};
        int[] intersection = intersection(nums1, nums2);
        System.out.println(Arrays.toString(intersection));
    }

    public static int[] intersection(int[] nums1, int[] nums2) {
        List<Integer> result = new ArrayList<>();
        Map<Integer, Integer> nums1Map = new HashMap<>();
        for (int key : nums1) {
            Integer count = nums1Map.get(key);
            if (count == null) {
                nums1Map.put(key, 1);
            } else {
                nums1Map.put(key, ++count);
            }
        }
        for (int key : nums2) {
            Integer count = nums1Map.get(key);
            if (count != null) {
                if (count > 0) {
                    result.add(key);
                }
                nums1Map.put(key, --count);
            }
        }
        // System.out.println(nums1Map);
        // System.out.println(result);
        return result.stream().mapToInt(x -> x).toArray();
    }
}
